package com.jy.api.controller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品二维码数据管理控制器
 *
 * @author fengshuonan
 * @Date 2018-07-27 22:35:25
 */
@Controller
@RequestMapping("anon/productionqr")
public class AutoLoginController {
    Map<String, Object> map2 = new HashMap<>();
    @RequestMapping("/login")
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpClientContext httpClientContext = HttpClientContext.create();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String kaptcha = "a8nd7";
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            HttpPost httpPost = new HttpPost("http://localhost:8446/login/sys");//登录请求url
            headerWrapper(httpPost);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//            httpPost.setHeader("Referer", "https://www.datalearner.com/signin");
            params.add(new BasicNameValuePair("username", "admin"));
            params.add(new BasicNameValuePair("password", "juice"));
            params.add(new BasicNameValuePair("captcha", kaptcha));
            params.add(new BasicNameValuePair("userType", "0"));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 发送请求
            HttpResponse httpresponse = httpClient.execute(httpPost,httpClientContext);
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity);
            System.out.println(body);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //从请求结果中获取Cookie，此时的Cookie已经带有登录信息了
        CookieStore cookieStore = httpClient.getCookieStore();
        List<org.apache.http.cookie.Cookie> list = cookieStore.getCookies();
        Map<String,String> map = new HashMap<String,String>();
        for (Cookie cookie : list) {
            map.put("version", String.valueOf(cookie.getVersion()));
            map.put("name", cookie.getName());
            map.put("value", cookie.getValue());
            map.put("domain", cookie.getDomain());
            map.put("path", cookie.getPath());
        }
        //这个CookieStore保存了我们的登录信息，我们可以先将它保存到redis缓存，后面直接读取使用
        map2.putAll(map);

        index(request,response,kaptcha);
    }

    @RequestMapping("/hp")
    public String hp(){
        CloseableHttpClient hc = null;
        CloseableHttpResponse response = null;
        try {
            HttpGet hg1 = new HttpGet("http://localhost:8446/webjars/index.html");//主页地址
            headerWrapper(hg1);
            //我们将之前存在redis中的Cookie读出来
            CookieStore cookieStore1 = getCookieStores();
            //构造一个带这个Cookie的HttpClient
            hc = HttpClientBuilder.create().setDefaultCookieStore(cookieStore1).build();
            response = hc.execute(hg1);
            HttpEntity entity1 = response.getEntity();
            String body1 = EntityUtils.toString(entity1);
            System.out.println(body1);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(response != null) {
                    response.close();
                }
                if(hc != null) {
                    hc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "hello hp";
    }
    public void index(HttpServletRequest request1, HttpServletResponse response1,String kaptcha) throws IOException {
//        http://localhost:8446/webjars/index.html
        String version = null;
        String name = null;
        String value = null;
        String domain = null;
        String path = null;
        version = map2.get("version").toString();
        name = map2.get("name").toString();
        value = map2.get("value").toString();
        domain = map2.get("domain").toString();
        path = map2.get("path").toString();
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, value);
        cookie.setVersion(Integer.parseInt(version));
        cookie.setDomain(domain);
        cookie.setValue(value);
        cookie.setPath(path);
        response1.addCookie(cookie);

        request1.getSession().setAttribute("KAPTCHA_SESSION_KEY",kaptcha);
        response1.sendRedirect("http://localhost:8446/webjars/index.html");

    }

    //从redis中取出携带登录信息的cookie
    public CookieStore getCookieStores(){
        BasicCookieStore cookieStore = null;
        //下面我们将演示如何使用Cookie来请求，首先我们将之前的Cookie读出来
//        Map<String, String> map2 = redisService.getHash("mykey");
        ;
        String version = null;
        String name = null;
        String value = null;
        String domain = null;
        String path = null;
        version = map2.get("version").toString();
        name = map2.get("name").toString();
        value = map2.get("value").toString();
        domain = map2.get("domain").toString();
        path = map2.get("path").toString();
        BasicClientCookie cookie = new BasicClientCookie(name, value);
        cookie.setVersion(Integer.parseInt(version));
        cookie.setDomain(domain);
        cookie.setValue(value);
        cookie.setPath(path);
        cookie.setExpiryDate(null);
        cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        return cookieStore;
    }
    public static void headerWrapper(AbstractHttpMessage methord) {
        methord.setHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0");
        methord.setHeader("accept", "*/*");
        methord.setHeader("accept-language", "zh-CN");
        methord.setHeader("Accept-Encoding", "gzip, deflate");
    }

}
